<template>
	<view class="build-product-container">
		<view class="top-info-container">
			<view class="tips-view" v-if="!vuex_currentTask">
				<text class="tips">·请在下面的列表中选择生产任务，点击“切换”，再点击“开始生产”。</text>
				<text class="tips">·结束生产，请点击“下工”按钮。</text>
			</view>

			<view class="info-view" v-if="vuex_currentTask">
				<view class="info-item">
					<text class="info-label">生产任务编号：</text>
					<text class="info-value">{{ vuex_currentTask.taskCode || '' }}</text>
				</view>

				<view class="info-item">
					<text class="info-label">生产编码：</text>
					<text class="info-value">{{ vuex_currentTask.itemCode || '' }}</text>
				</view>

				<view class="info-item">
					<text class="info-label">产品名称：</text>
					<text class="info-value">{{ (vuex_currentTask.clientName || '') + '' + (vuex_currentTask.itemName || '') }}</text>
				</view>

				<view class="total-view">
					<text class="total-label">排产数量</text>
					<text class="total-value">{{ vuex_currentTask.quantity || '0' }}</text>
				</view>
				<view class="total-info-view">
					<view class="total-type-view">
						<text class="total--type-label">已生产数量</text>
						<text class="total-type-value">{{ vuex_currentTask.quantityProduced || '0' }}</text>
					</view>
					<view class="total-type-view">
						<text class="total--type-label">合格品数量</text>
						<text class="total-type-value">{{ vuex_currentTask.quantityQuanlify || '0' }}</text>
					</view>
					<view class="total-type-view">
						<text class="total--type-label">不良品数量</text>
						<text class="total-type-value">{{ vuex_currentTask.quantityUnquanlify || '0' }}</text>
					</view>
				</view>
			</view>
			<view class="button-group-view">
				<view v-if="!vuex_currentTask || vuex_currentTask.status != 'START'" class="button-item button-item-right-border" @click="startBuild">
					<image src="../../../static/aidex/product/icon_product_start.png" class="button-img"></image>
					<text class="button-txt">开始生产</text>
				</view>
				<view v-if="vuex_currentTask && vuex_currentTask.status == 'START'" class="button-item button-item-right-border" @click="pauseBuild">
					<image src="../../../static/aidex/product/icon_product_pause.png" class="button-img"></image>
					<text class="button-txt">暂停生产</text>
				</view>
				<view class="button-item button-item-right-border" @click="workReport">
					<image src="../../../static/aidex/product/icon_product_update.png" class="button-img"></image>
					<text class="button-txt">报工</text>
				</view>
				<view class="button-item button-item-right-border" @click="sopEvent">
					<image src="../../../static/aidex/product/icon_product_sop.png" class="button-img"></image>
					<text class="button-txt">标准作业</text>
				</view>
				<view class="button-item button-item-right-border" @click="flowSheet">
					<image src="../../../static/aidex/product/icon_product_dy.png" class="button-img"></image>
					<text class="button-txt">新增流转单</text>
				</view>
				<view class="button-item" @click="stopBuild">
					<image src="../../../static/aidex/product/icon_product_stop.png" class="button-img"></image>
					<text class="button-txt">下工</text>
				</view>
			</view>
		</view>
		<view class="contet-list-container">
			<item v-if="!vuex_currentTask || vuex_currentTask.taskId != task.taskId" v-for="(task, index) in taskList" :key="index" :task="task" @changeTask="changeTask"></item>
		</view>
		<uni-load-more
			iconType="auto"
			:content-text="{
				contentdown: '向上滑动，加载更多',
				contentrefresh: '加载中...',
				contentnomore: '没有更多...'
			}"
			:status="loadStatus"
		></uni-load-more>
	</view>
</template>

<script>
import Item from './components/item/index.vue';
const PAGESIZE = 10;
export default {
	components: {
		Item
	},
	data() {
		return {
			taskList: [],
			pageIndex: 1,
			berforePageIndex: 1,
			taskTotal: 0,
			loadStatus: 'more'
			/**
				 *  more	加载前
				   loading	加载中
				   no-more	没有更多数据
				 * **/
		};
	},
	onLoad(options) {
		this.$u.vuex('vuex_currentTask', '');
		uni.$on('build_product_updataTask', () => {
			this.refreshData(true);
		});
		uni.showLoading({
			title: '加载中...',
			icon: 'none'
		});
		uni.showLoading({
			title: '加载中...',
			icon: 'none'
		});
		this.loadStatus = 'loading';
		Promise.all([
			this.$u.api.task.getAllTask({
				workstationCode: this.vuex_bind_workstation_code,
				pageSize: 10,
				pageNum: this.pageIndex
			}),
			this.$u.api.task.getAllTask({
				workstationCode: this.vuex_bind_workstation_code,
				pageSize: 10,
				pageNum: this.pageIndex,
				status: 'START'
			})
		])
			.then(res => {
				uni.hideLoading();
				this.taskTotal = res[0]?.total || 0;
				const resTaskList = res[0]?.rows || [];
				this.taskList.splice(0, this.taskList.length, ...resTaskList);
				const startResTaskList = res[1].rows || [];
				if (startResTaskList.length > 0) {
					this.$u.vuex('vuex_currentTask', startResTaskList[0]);
				}
				if (this.taskList.length >= this.taskTotal) {
					this.loadStatus = 'no-more';
				} else {
					this.loadStatus = 'more';
				}
			})
			.catch(err => {
				console.log(err);
				uni.hideLoading();
				if (this.taskList.length >= this.taskTotal) {
					this.loadStatus = 'no-more';
				} else {
					this.loadStatus = 'more';
				}
			});
	},
	onNavigationBarButtonTap(button) {
		if (button.id == 'scanType') {
			this.appNavTo();
		}
	},
	onPullDownRefresh() {
		this.refreshData(true);
	},
	onReachBottom() {
		this.refreshData(false);
	},
	methods: {
		appNavTo() {
			// uni.navigateTo({
			// 	url:`/pages/sys/scan_flow_sheet/index?transorder=${"TRANS20230222001"}`
			// })
			// return;
			// #ifdef APP-PLUS
			const pluginImpl = uni.requireNativePlugin('KTGPlugins-QRCode');
			if (pluginImpl) {
				pluginImpl.goToScanPage(
					{
						isQrcode: true
					},
					data => {
						console.log(data);
						if (data.code == 'success' && data.data) {
							const codeData = data.data;
							console.log(codeData);
							const code = codeData.split('-')[1];
							if (code) {
								uni.navigateTo({
									url: `/pages/sys/scan_flow_sheet/index?transorder=${code}`
								});
							} else {
								uni.showToast({
									title: '二维码错误',
									icon: 'none'
								});
							}
						}
					}
				);
			} else {
				uni.showToast({
					title: '失败',
					icon: 'none'
				});
			}

			// #endif
		},
		refreshData(isRefresh) {
			if (isRefresh) {
				this.pageIndex = 1;
			} else {
				if (this.resTaskList.length >= this.taskTotal) {
					return;
				}
				this.pageIndex += 1;
			}

			this.loadStatus = 'loading';
			uni.showLoading({
				title: '加载中...',
				icon: 'none'
			});
			this.$u.api.task
				.getAllTask({
					workstationCode: this.vuex_bind_workstation_code,
					pageSize: 10,
					pageNum: this.pageIndex
				})
				.then(res => {
					const resTaskList = res?.rows || [];
					this.taskTotal = res?.total || 0;
					this.berforePageIndex = this.pageIndex;
					if (this.pageIndex == 1) {
						this.taskList.splice(0, this.taskList.length, ...resTaskList);
					} else {
						this.taskList.push(...resTaskList);
					}
					uni.hideLoading();
					uni.stopPullDownRefresh();
					if (this.taskList.length >= this.taskTotal) {
						this.loadStatus = 'no-more';
					} else {
						this.loadStatus = 'more';
					}
				})
				.catch(err => {
					console.log(err);
					uni.stopPullDownRefresh();
					this.pageIndex = this.berforePageIndex;
					if (this.taskList.length >= this.taskTotal) {
						this.loadStatus = 'no-more';
					} else {
						this.loadStatus = 'more';
					}
					uni.hideLoading();
				});
		},
		async startBuild() {
			if (!this.vuex_currentTask) {
				uni.showToast({
					title: '当前未选中任务',
					icon: 'none'
				});
				return;
			}
			if (this.vuex_currentTask.status == 'START') {
				uni.showToast({
					title: '当前任务已开始',
					icon: 'none'
				});
				return;
			}
			if (this.vuex_currentTask.status == 'FINISHED') {
				uni.showToast({
					title: '当前任务已结束',
					icon: 'none'
				});
				return;
			}
			try {
				const res = await this.$u.api.task.taskChange({
					taskId: this.vuex_currentTask.taskId,
					status: 'START'
				});
				const task = Object.assign(this.vuex_currentTask, { status: 'START' });
				this.$u.vuex('vuex_currentTask', task);
				await this.refreshData(true);
			} catch (e) {
				//TODO handle the exception
				console.log(e);
			}
		},
		async pauseBuild() {
			if (this.vuex_currentTask.status != 'START') {
				uni.showToast({
					title: '当前任务未开始',
					icon: 'none'
				});
				return;
			}
			try {
				const res = await this.$u.api.task.taskChange({
					taskId: this.vuex_currentTask.taskId,
					status: 'PAUSE'
				});
				const task = Object.assign(this.vuex_currentTask, { status: 'PAUSE' });
				this.$u.vuex('vuex_currentTask', task);
				await this.refreshData(true);
			} catch (e) {
				//TODO handle the exception
				console.log(e);
			}
		},
		workReport() {
			if (!this.vuex_currentTask) {
				uni.showToast({
					title: '当前没有生产任务',
					icon: 'none'
				});
				return;
			}
			uni.navigateTo({
				url: `/pages/sys/work_report/index?mode=add`
			});
		},
		sopEvent() {
			if (!this.vuex_currentTask) {
				uni.showToast({
					title: '当前没有生产任务',
					icon: 'none'
				});
				return;
			}
			uni.navigateTo({
				url: `/pages/sys/sop/index`
			});
		},
		flowSheet() {
			if (!this.vuex_currentTask) {
				uni.showToast({
					title: '当前没有生产任务',
					icon: 'none'
				});
				return;
			}
			uni.navigateTo({
				url: `/pages/sys/print_the_flow_sheet/index`
			});
		},
		stopBuild() {
			if (!this.vuex_bind_workstation_code) {
				uni.showToast({
					title: '当前未绑定站点',
					icon: 'none'
				});
				return;
			}
			uni.showModal({
				title: '确认下工',
				content: '是否确认确认下工？',
				showCancel: true,
				cancelText: '取消',
				confirmText: '确认',
				success: res => {
					if (res.confirm) {
						// 用户点击确定
						this.$u.api.workstation
							.workstation({
								workstationCode: this.vuex_bind_workstation_code,
								userId: this.vuex_user.userId,
								operationFlag: 'N'
							})
							.then(res => {
								this.$u.vuex('vuex_bind_workstation_code', '');
								this.$u.vuex('vuex_currentTask', '');
								this.taskList = [];
								uni.navigateBack({
									delta: 1
								});
							})
							.catch(err => {
								console.log(err);
							});
					} else {
						// 否则点击了取消
					}
				}
			});
		},
		changeTask(task) {
			if (this.vuex_currentTask && this.vuex_currentTask.status == 'START') {
				uni.showModal({
					title: '确认切换',
					content: '当前已经有任务正在进行中，是否暂停当前任务？',
					showCancel: true,
					cancelText: '取消',
					confirmText: '确认',
					success: async res => {
						if (res.confirm) {
							try {
								const res = await this.$u.api.task.taskChange({
									taskId: this.vuex_currentTask.taskId,
									status: 'PAUSE'
								});
								this.$u.vuex('vuex_currentTask', task);
								await this.refreshData(true);
							} catch (e) {
								//TODO handle the exception
								console.log(err);
							}
						}
					}
				});
			} else {
				this.$u.vuex('vuex_currentTask', task);
			}
		}
	}
};
</script>

<style lang="scss">
.build-product-container {
	.top-info-container {
		background-color: #1c2334;
		.tips-view {
			height: 396rpx;
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			justify-content: center;
			padding: 0 20rpx;
			.tips {
				padding: 20rpx 0;
				line-height: 40rpx;
				color: #fff;
				font-size: 28rpx;
			}
		}
		.info-view {
			display: flex;
			height: 396rpx;
			flex-direction: column;
			flex: 1;
			.info-item {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				line-height: 60rpx;
				padding: 0 20rpx;
				.info-label {
					font-size: 28rpx;
					color: #fff;
				}
				.info-value {
					font-size: 28rpx;
					color: #fff;
				}
			}
			.total-view {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				.total-label {
					color: #fff;
					font-size: 28rpx;
					line-height: 40rpx;
				}
				.total-value {
					line-height: 70rpx;
					font-size: 50rpx;
					color: #fff;
				}
			}
			.total-info-view {
				display: flex;
				flex-direction: row;
				flex: 1;
				margin-top: 20rpx;
				.total-type-view {
					display: flex;
					flex-direction: column;
					flex: 1;
					align-items: center;
					justify-content: center;
					.total--type-label {
						color: #fff;
						font-size: 28rpx;
						line-height: 40rpx;
					}
					.total-type-value {
						color: #fff;
						font-size: 28rpx;
						line-height: 40rpx;
					}
				}
			}
		}
		.button-group-view {
			margin-top: 20rpx;
			display: flex;
			flex: 1;
			flex-direction: row;
			border-top: 1px solid #fff;
			.button-item-right-border {
				border-right: 1px solid #fff;
				padding: 30rpx 0;
			}
			.button-item {
				margin: 20rpx 0;
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.button-img {
					width: 60rpx;
					height: 60rpx;
				}
				.button-txt {
					margin-top: 5rpx;
					font-size: 26rpx;
					color: #fff;
				}
			}
		}
	}
}
</style>
